package org.third.security.crypto;

import org.apache.commons.codec.binary.Hex;

import java.io.InputStream;
import java.security.MessageDigest;

public class FileSum {
    /**
     * Used to build output as Hex
     */
    private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    /**
     * Used to build output as Hex
     */
    private static final char[] DIGITS_UPPER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };

    /**
     * Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
     * The returned array will be double the length of the passed array, as it takes two characters to represent any
     * given byte.
     *
     * @param data a byte[] to convert to Hex characters
     * @param toDigits the output alphabet
     * @return A char[] containing hexadecimal characters
     */
     static char[] encodeHex(byte[] data, boolean toLower) {
        char[] toDigits = toLower?DIGITS_LOWER:DIGITS_UPPER;
        int l = data.length;
        char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
            out[j++] = toDigits[0x0F & data[i]];
        }
        return out;
    }

    public static void main(String[] args) throws Exception {
        InputStream fin = FileSum.class.getClassLoader()
                .getResourceAsStream("seeded/com.microfocus.cdf__2018.01.0098__Add_Update_User.json");
        byte[] buf = new byte[fin.available()];
        fin.read(buf);

        MessageDigest md5 = MessageDigest.getInstance("SHA-224");//MD5, SHA-1/224/256/384/512
        md5.update(buf);
        byte[] tmp = md5.digest();

        System.out.println(new String(encodeHex(tmp,true)));
        //
        // System.out.println( DigestUtils.md5Hex(fin));
    }
}
